今天是紀錄LeetCode解題的第十一天
第十一題題目:You are given an integer array height of length n. Find two lines that together with the x-axis form a container, such that the container contains the most water.
給定一個長度為n的整數數組,找到兩條線與X軸形成的容器能裝最多的水
定義雙指針l、r,l從最左邊開始,r從最右邊,算出容器能裝多少水(兩個長度的索引相減*數值小的長度),因為長度高的可以裝較多的水,所以看l、r誰小誰就往下一個索引移動
class Solution:
def maxArea(self, height: List[int]) -> int:
area = 0
l,r = 0 , len(height) - 1
while l < r:
area = max(area,min(height[l],height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return area
這題是很簡單的雙指針應用,後續過幾天會有稍微複雜一點的雙指針題目,可以先在簡單題把觀念釐清,了解執行過程與原理